<template>
  <div>
    <el-drawer
      :title="this.id > 0 ? '编辑' : '新增'"
      :visible.sync="drawer"
      direction="rtl"
      :show-close="true"
      :wrapper-closable="true"
      :append-to-body="true"
      :wrapperClosable="false"
      :before-close="handleClose"
      :size="`45%`"
    >
      <div class="mt14" v-if="importTemplate.widgetList.length" v-loading="formloading">
        <VFormRender
          v-if="drawer"
          ref="preForm"
          :form-json="importTemplate"
          :form-data="testFormData"
          :preview-state="true"
          :option-data="testOptionData"
          :global-dsv="designerDsv"
        >
        </VFormRender>
        <div class="button from-foot-btn fix btn-shadow">
          <el-button size="small" class="el-btn" @click="handleClose">取消</el-button>
          <el-button size="small" type="primary" :loading="loading" @click="saveFn">保存</el-button>
        </div>
      </div>
      <div v-else>
        <default-page :index="16" :min-height="420" />
      </div>
    </el-drawer>
  </div>
</template>
<script>
import VFormRender from '@/components/form-render/index'
import defaultPage from '@/components/common/defaultPage'
import { crudModuleCreateApi, crudModuleSaveDataApi, crudModuleUpdateApi, crudFangkeSaveApi, 
  crudFangkeuserCreateApi, crudFangkeCarCreateApi, crudFangkevistortrqrApi } from '@/api/develop'
import { FacialVerificationApi } from '@/api/enterprise'
import { CLOSE_NODE_ICON_TOOLBAR } from '@/components/xmind-editor/event-constant'
import ApiUrl from '@/api/apiUrls' // dengshunbo 2024-12-27新增
export default {
  name: '',
  components: { VFormRender, defaultPage },
  props: {
    keyName: {
      type: String,
      default: ''
    },
    crud: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      drawer: false,
      importTemplate: {
        formConfig: {},
        widgetList: []
      },
      title: '新增',
      id: 0, // 当前列表的id值
      designer: {},
      testFormData: {},
      loading: false,
      testOptionData: {
        select62173: [
          { label: '01', value: 1 },
          { label: '22', value: 2 },
          { label: '333', value: 3 }
        ],

        select001: [
          { label: '辣椒', value: 1 },
          { label: '菠萝', value: 2 },
          { label: '丑橘子', value: 3 }
        ]
      },
      formloading: false,
      drawerData:{},
    }
  },
  computed: {
    designerDsv() {
      return this.globalDsv
    }
  },

  methods: {
    async openBox(id, data) {
      console.log("Adddd")
      if (id) {
        this.id = id
        this.drawerData = data; // dengshunbo 2025-3-17 获取查看详情数据
      } else {
        this.$set(this, 'testFormData', {})
      }
      let obj = {}
      if (this.crud) {
        obj.crud_id = this.crud.crud_id
        obj.crud_value = this.crud.crud_value
      } else {
        obj = {}
      }
      obj.id = this.id
      const res = await crudModuleCreateApi(this.keyName, obj)
      if (res.data.form_info && res.data.form_info.global_options) {
        this.$set(this.importTemplate, 'formConfig', res.data.form_info.global_options)
      }
      this.$set(this.importTemplate, 'widgetList', res.data.form_info.options)
      // dengshunbo 2025-1-20 改
      console.log("data", data)
      if (data) {
        // dengshunbo 2025-1-20
        if(this.keyName=="fangkeguanli"){

          if(data.module_info.shouquanmenjinzu){
             let meji = data.module_info.shouquanmenjinzu.split(",")
             data.module_info.shouquanmenjinzu = meji;
          }else{
             data.module_info.shouquanmenjinzu = ''
          }
          this.$set(this, 'testFormData', data.module_info)
        }else{
          this.$set(this, 'testFormData', data.module_info)
        }
      }
      // end
      // 原代码
      // if (data) {
      //   this.$set(this, 'testFormData', data.module_info)
      // }
      this.drawer = true
    },

    saveFn() {
      this.$refs['preForm']
        .getFormData()
        .then((formData) => {
          if (this.id > 0) { // 编辑
            // dengshunbo 2025-3-17
            if(this.keyName=="fangkeguanli"){
              this.formloading = true;
              if(formData.face_thumb.length == 0){
                 formData.face_thumb  = ''
              }
              if(formData.face_thumb){
                let faceData = {face_thumb:  formData.face_thumb[0].url} // 实拍图效验form数据
                if(this.drawerData.module_info.face_thumb && this.drawerData.module_info.face_thumb.length > 0){ // 判断是否有编辑前是否存在实拍头像
                    if(this.drawerData.module_info.face_thumb[0].url != faceData.face_thumb){ // 判断实拍头像是否有变化
                      this.handlerFacialVerification(faceData, formData, this.id)
                    }else{ // 没有变化直接调用更新接口
                      if(formData.shouquanmenjinzu){
                          let meji = formData.shouquanmenjinzu.join(",")
                          formData.shouquanmenjinzu = meji
                      }else{
                          formData.shouquanmenjinzu = ''
                      }
                      this.upladData(this.id, formData)
                    }
                }else{ // 新增时没有添加实拍头像，编辑时已加入进行人脸效验
                  this.handlerFacialVerification(faceData, formData, this.id)
                }
              }else{ // 编辑时未提交实拍头像-直接调用更新接口
                if(formData.shouquanmenjinzu){ // 对授权门禁组数据进行处理后提交
                    let meji = formData.shouquanmenjinzu.join(",")
                    formData.shouquanmenjinzu = meji
                }else{
                    formData.shouquanmenjinzu = ''
                }
                this.upladData(this.id, formData)
              }
              // end
            }else{ // 员代码
              this.upladData(this.id, formData)
            }
          } else {
            // dengshunbo 2025-1-14 访客新增调后台接口
            if(this.keyName=="fangkeguanli"){
              this.formloading = true;
              if(formData.face_thumb.length == 0){
                 formData.face_thumb  = ''
              }
              let userinfoobj = JSON.parse(localStorage.getItem('userInfo'));
              formData.yaoqingrenxingming = userinfoobj.name
              if(formData.face_thumb){
                let faceData = {face_thumb:  formData.face_thumb[0].url}
                 this.handlerFacialVerification(faceData, formData)
              }else{
                if(formData.shouquanmenjinzu){
                    let meji = formData.shouquanmenjinzu.join(",")
                    formData.shouquanmenjinzu = meji
                }else{
                    formData.shouquanmenjinzu = ''
                }
                this.savaData(formData)
              }
            }else{
              // 原代码
              this.savaData(formData)
            }
          }
        })
        .catch((error) => {
          this.$message.error(error)
        })
    },
    // 实体列表新增保存
    savaData(data) {
      console.log("data", data)
      this.loading = true
      if (this.crud) {
        data.crud_id = this.crud.crud_id
        data.crud_value = this.crud.crud_value
      }
      // dengshunbo 2025-1-14 访客新增调后台接口
      console.log("keyName", this.keyName)
      if(this.keyName == 'fangkeguanli'){ 
        this.formloading = false;
        data.yaoqinglianjie = "";
        data.fangkeleixing = 1;
        crudFangkeSaveApi(data)
        .then((res) => {
            if (res.status == 200) {
               // 调用修改生成访客邀请链接接口
                const key = 12345999;
                let dids = this.encrypt(res.data.id, key)
                let yaoqinglianjie = ApiUrl + "/work/visitor/index.html?id="+dids;
                data.yaoqinglianjie = yaoqinglianjie;
                this.FKupladData(res.data.id, data);// 生产邀请链接
                // end
                // 访客是否下发授权
                console.log("data", data)
                if(data.daofangzhuangtai==2 && data.shoujihaoma){ // 访客状态为访客 且 手机号码不为空
                  this.getFkUserCreate(res.data.id, data) // 访客下发授权接口
                  // 访客车辆下发
                  if(data.chepaihaoma && data.cheliangdisanfangpingtaiID !=1){
                     crudFangkeCarCreateApi(res.data.id)
                  }
                }
            }else{
               this.$message.error(res.message)
            }
            this.loading = false
          })
          .catch((err) => {
            this.loading = false
          })
        // end
      }else{ // 非访客管理调用原代码
        // 原代码
        crudModuleSaveDataApi(this.keyName, data)
        .then((res) => {
          if (res.status == 200) {
            this.handleClose()
            this.$emit('getList')
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
      }
    },
    // dengshunbo 2025-1-14 访客新增调后台接口
    handlerFacialVerification(faceobj, formdata, id=0){
      FacialVerificationApi(faceobj).then((res)=>{
        if(res.data.code==200){
           if(res.data.data){
              if(formdata.shouquanmenjinzu){
                  let meji = formdata.shouquanmenjinzu.join(",")
                  formdata.shouquanmenjinzu = meji
              }else{
                formdata.shouquanmenjinzu = ''
              }
              if(id==0){
                this.savaData(formdata)
              }else{
                this.upladData(this.id, formdata)
              }
           }else{
              this.$message.error("实拍头像识别失败,请检查头像是否清晰或正确")
           }
        }else{
          this.$message.error(res.data.message)
        }
      }).catch((err)=>{
        if(err.data.code==200){
           if(err.data.data){
              if(formdata.shouquanmenjinzu){
                  let meji = formdata.shouquanmenjinzu.join(",")
                  formdata.shouquanmenjinzu = meji
              }else{
                formdata.shouquanmenjinzu = ''
              }
              if(id==0){
                this.savaData(formdata)
              }else{
                this.upladData(this.id, formdata)
              }
           }else{
              this.formloading = false;
              this.$message.error("实拍头像识别失败,请检查头像是否清晰或正确")
           }
        }else{
          this.formloading = false;
          this.$message.error(err.data.message)
        }
      })
    },
    // 访客更新添加邀请链接
    FKupladData(id, data){
      let dataobj = {}
      if (this.crud) {
        dataobj.crud_id = this.crud.crud_id
        dataobj.crud_value = this.crud.crud_value
      }
      dataobj.yaoqinglianjie = data.yaoqinglianjie;
      crudModuleUpdateApi(this.keyName, id, data)
        .then((res) => {
          if (res.status == 200) {
            this.handleClose()
            this.$emit('getList')
          }
        })
        .catch((err) => {
          this.loading = false
        })
    },
    encrypt(num, key=12345999) {
        return num * key;
    },
    // 访客下发授权接口
    getFkUserCreate(id, data){
      crudFangkeuserCreateApi(id).then((res)=>{
        if(!data.shouquanerweima){
          let formdata1={
            id: id,
            door_arr: data.shouquanmenjinzu,
            start_time: data.jihuadaofangriqi,
            end_time: data.jihualikaishijian,
          }
          crudFangkevistortrqrApi(formdata1)
        }
      }).catch((err)=>{
        if(!data.shouquanerweima){
          let formdata1={
            id: id,
            door_arr: data.shouquanmenjinzu,
            start_time: data.jihuadaofangriqi,
            end_time: data.jihualikaishijian,
          }
          crudFangkevistortrqrApi(formdata1)
        }
      })
    },
    // end
    // 实体列表更新保存
    upladData(id, data) {
      this.loading = true
      if (this.crud) {
        data.crud_id = this.crud.crud_id
        data.crud_value = this.crud.crud_value
      }
      if(this.keyName=="fangkeguanli"){
        this.formloading = false;
        const key = 12345999;
        let dids = this.encrypt(id, key)
        let yaoqinglianjie = ApiUrl + "/work/visitor/index.html?id="+dids;
        data.yaoqinglianjie = yaoqinglianjie;
      }
      // 原代码
      crudModuleUpdateApi(this.keyName, id, data)
        .then((res) => {
          if (res.status == 200) {
            this.handleClose()
            this.$emit('getList')
            if(this.keyName == 'fangkeguanli'){ 
               // 访客是否下发授权
               console.log("data", data)
                if(data.daofangzhuangtai==2 && data.shoujihaoma){ // 访客状态为访客 且 手机号码不为空
                  // if(data.face_thumb.length > 0){ // 访客头像不为空
                  //   let jhtime = this.hadnlerFilterReturn(data.jihuadaofangriqi) // 计划到访日期时间戳
                  //   let sjtime = this.hadnlerFilterReturn(); // 当前日期时间戳
                  //   if(jhtime < sjtime)
                  //     this.getFkUserCreate(id) // 访客下发授权接口
                  // }
                  let jhtime = this.hadnlerFilterReturn(data.jihuadaofangriqi) + 86500000 // 计划到访日期时间戳
                  let sjtime = this.hadnlerFilterReturn(); // 当前日期时间戳
                  console.log("AA",jhtime, sjtime);
                  console.log(jhtime > sjtime)
                  if(jhtime > sjtime){ 
                      // 访客人员下发
                      this.getFkUserCreate(id, data) // 访客下发授权接口
                  }
                  // 访客车辆下发
                  if(data.chepaihaoma && data.cheliangdisanfangpingtaiID !=1){
                     crudFangkeCarCreateApi(id)
                  }
                }
            }
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
      
    },

    handleClose() {
      // this.$refs['preForm'].resetForm()
      this.drawer = false
      this.id = 0
    },
    // dengshunbo 2025-1-14 时间戳转换
    hadnlerFilterReturn(time=''){
      let rtime = ''
      if(time){
        rtime = new Date(time).getTime();
      }else{
        rtime = new Date().getTime();
      }
      return rtime;
    }
    
    
  }
}
</script>
<style scoped lang="scss">
/deep/.el-drawer__body {
  padding: 10px 20px 50px 20px;
}
.p10 {
  width: 100%;
  padding: 0 10px;
}
</style>
